const jwt = require("jsonwebtoken");
const md5 = require("md5");
const path = require("path");
const multer = require("multer");
const { UnknownError } = require("./errors");

//处理 解析token
const analysisToken = (token) => {
  const result = jwt.verify(token.split(" ")[1], md5(process.env.JWT_SECRYT));
  return result;
};

//处理数组形式数据
const handleDataArr = (data) => {
  const arr = [];
  for (const iterator of data) {
    arr.push(iterator.dataValues);
  }
  return arr;
};

//上传文件处理
const storage = multer.diskStorage({
  //文件存储位置
  destination(req, file, cb) {
    cb(null, path.resolve(__dirname, "../public/static", "uploads"));
  },
  //上传到服务器的文件名处理
  filename(req, file, cb) {
    cb(
      null,
      `${Date.now()}_${Math.random().toString(36).slice(-5)}_${
        file.originalname
      }`
    );
  },
});
const uploading = multer({
  storage: storage,
  limits: {
    fieldSize: 2000000,
    files: 1,
  },
});

//获取markdown文档的TOC
const getMarkDownTOC = (info) => {
  const toc = require("markdown-toc");
  const result = toc(info.markdownContent).json;

  /**
   * 生成TOC对象
   * @param {*} flatArr
   */
  function transfer(flatArr) {
    const stack = [];
    const result = [];
    let min = 6; //标题最小级别

    /**
     * 创建toc对象
     * @param {*} item
     * @returns
     */
    function creatTOCItme(item) {
      return {
        name: item.content,
        anchor: item.slug,
        level: item.lvl,
        children: [],
      };
    }

    /**
     * 处理每个需要加入到toc里面的children项
     * @param {*} item
     */
    function handleItem(item) {
      const top = stack[stack.length - 1]; //得到栈顶的最后一个数据 || undefined
      if (!top) {
        stack.push(item);
      } else if (item.level > top.level) {
        //当前toc对象为栈顶子项
        top.children.push(item);
        stack.push(item);
      } else {
        stack.pop(); //当前栈顶出栈
        handleItem(item);
      }
    }

    //寻找到最小标题等级
    for (const i of flatArr) {
      if (i.lvl < min) {
        min = i.lvl;
      }
    }
    for (const item of flatArr) {
      const tocItem = creatTOCItme(item);
      if (tocItem.level === min) {
        //当前toc等级为最低等级，不会作为其他 toc 的 children
        result.push(tocItem);
      }
      //处理需要加入 toc 的 children
      handleItem(tocItem);
    }
    return result;
  }
  info.toc = transfer(result);
  delete info.markdownContent;

  //处理html文档中的锚点信息
  for (const item of result) {
    switch (item.lvl) {
      case 1: {
        const anchor = `<h1 id=${item.slug}>`;
        info.htmlContent = info.htmlContent.replace("<h1>", anchor);
        break;
      }
      case 2: {
        const anchor = `<h2 id=${item.slug}>`;
        info.htmlContent = info.htmlContent.replace("<h2>", anchor);
        break;
      }
      case 3: {
        const anchor = `<h3 id=${item.slug}>`;
        info.htmlContent = info.htmlContent.replace("<h3>", anchor);
        break;
      }
      case 4: {
        const anchor = `<h4 id=${item.slug}>`;
        info.htmlContent = info.htmlContent.replace("<h4>", anchor);
        break;
      }
      case 5: {
        const anchor = `<h5 id=${item.slug}>`;
        info.htmlContent = info.htmlContent.replace("<h5>", anchor);
        break;
      }
      case 6: {
        const anchor = `<h6 id=${item.slug}>`;
        info.htmlContent = info.htmlContent.replace("<h6>", anchor);
        break;
      }
    }
  }

  return info;
};

//整理Project返回值格式
const handleProject = (arr) => {
  //将项目介绍字符串分割为数组
  for (const item of arr) {
    item.description = item.description.split(";");
  }
  //根据 order 排序返回
  return arr.sort((a, b) => a.order - b.order);
};

//读取头像目录获取随机头像
const getAvatarPath = async () => {
  const path = require("path");
  const fs = require("fs");
  /**
   * 获取该目录下有几个文件
   * @param {*} dir
   * @returns
   */
  async function getDirLength(dir) {
    return new Promise((resolve) => {
      fs.readdir(dir, (err, files) => {
        if (err) {
          throw new UnknownError();
        } else {
          resolve(files);
        }
      });
    });
  }
  //目录地址
  const dir = path.resolve(__dirname, "../public/static", "avatar");

  const files = await getDirLength(dir); //文件列表
  const randomIndex = Math.floor(Math.random() * files.length); //随机下标

  return `/static/avatar/${files[randomIndex]}`;
};

module.exports = {
  analysisToken,
  handleDataArr,
  uploading,
  getMarkDownTOC,
  handleProject,
  getAvatarPath,
};
